<template>
  <div class="app-container">
    <el-card class="box-card">
      <el-form ref="formRef" :model="model" :rules="rules" class="" label-width="100px">
        <el-form-item label="头像" prop="full_avatar">
          <single-upload :single-file="model.single_file" :show-file-list="false" accept="image/jpeg, image/png, image/gif" @uploadCallback="singleCallback"/>
        </el-form-item>
        <el-form-item label="账号" prop="username">
          <el-input v-model="model.username" placeholder="请输入账号" clearable/>
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="model.nickname" placeholder="请输入昵称" clearable/>
        </el-form-item>
        <el-form-item label="手机" prop="phone">
          <el-input v-model="model.phone" clearable/>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="model.email" clearable/>
        </el-form-item>
        <el-form-item>
          <el-button :loading="btnLoading" type="primary" @click="save">保存</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import SingleUpload from '@/components/FileUpload'
import {profile, saveProfile} from '@/api/admin/admin'

export default {
  name: 'AdminProfile',
  components: {SingleUpload},
  data() {
    return {
      loading: false,
      btnLoading: false,
      model: {
        id: '',
        avatar: '',
        full_avatar: '',
        single_file: {},
        username: '',
        nickname: '',
        phone: '',
        email: '',
        remark: ''
      },
      rules: {
        username: [{required: true, message: '请输入账号', trigger: 'blur'}],
        nickname: [{required: true, message: '请输入昵称', trigger: 'blur'}]
      }
    }
  },
  created() {
    this.info()
  },
  methods: {
    info(msg = false) {
      this.loading = true
      profile({
        id: this.model.id
      }).then(res => {
        let data = res.data
        data.single_file = {
          url: data.full_avatar,
          path: data.avatar
        }

        this.model = data
        this.loading = false
        if (msg) {
          this.$message.success(res.msg)
        }
      }).catch(() => {
        this.loading = false
      })
    },
    // 保存
    save() {
      this.$refs['formRef'].validate(valid => {
        if (valid) {
          this.btnLoading = true
          saveProfile(this.model, 'post').then(res => {
            this.btnLoading = false
            this.list()
            this.$message.success(res.msg)
          }).catch(() => {
            this.btnLoading = false
          })
        }
      })
    },

    // 文件上传回调
    singleCallback(singleFile) {
      this.model.single_file = singleFile
      this.model.avatar = singleFile.path
      this.model.full_avatar = singleFile.url
    }
  }
}
</script>
